package com.xpgk.mvc.organization;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantInit;
import com.xpgk.constant.ConstantRender;
import com.xpgk.dto.RenderBean;
import com.xpgk.dto.ZtreeNode;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.dept.Department;
import com.xpgk.mvc.deptStation.DeptStation;
import com.xpgk.mvc.deptStation.DeptStationRight;
import com.xpgk.mvc.deptStation.DeptStationService;
import com.xpgk.mvc.organizationLevel.OrganLevel;
import com.xpgk.mvc.organizationLevel.OrganLevelRight;
import com.xpgk.mvc.productPrice.Price;
import com.xpgk.mvc.right.Right;
import com.xpgk.mvc.user.User;
import com.xpgk.mvc.user.UserService;
import com.xpgk.tools.ToolRandoms;
import com.xpgk.tools.security.ToolIDEA;
import com.xpgk.tools.security.ToolPbkdf2;

@Service(name = OrganizationService.serviceName)
public class OrganizationService extends BaseService {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(OrganizationService.class);

	public static final String serviceName = "organizationService";
	
	/**
	 * 添加机构
	 * @param cancelNodes
	 * @param organ
	 * @param user
	 * @return
	 * @throws Exception 
	 */
	@Before(Tx.class)
	public RenderBean addOrgan(List<ZtreeNode> cancelNodes, Organization organ, User user,String organIds) throws Exception{
		RenderBean result = new RenderBean();
		// 更改父节点状态
		Organization parentOrgan = Organization.dao.findById(organ.getStr(Organization.column_parentIds));
		parentOrgan.set(Organization.column_isparent, "true").update();
		int count = Db.queryNumber(getSqlMy(Organization.sqlId_childCount), organ.getStr(Organization.column_parentIds)).intValue();
		String username=user.getStr(User.column_username);
		String orgname = organ.getStr(Organization.column_name);
		Organization org= Organization.dao.findFirst("select *  from sys_organization  where  name  = ? LIMIT 1",orgname);
		if(org==null){
		Price price= Price.dao.findFirst("select *  from sb_shop_price  where  organizationIds  = ? LIMIT 1",organIds);	
		// 添加机构
		int orderid = count + 1;
		String pBh = parentOrgan.getStr(Organization.column_bh);
		int plevel = parentOrgan.getInt(Organization.column_level)+1;
		
		
		
		if(plevel>2&&StringUtils.isBlank(username)){
			result.setCode(ConstantRender.render_error_code);
			result.setMsg("请填写用户信息!");
			return result;
		}
		
		if(plevel==3&&price==null){
			result.setCode(ConstantRender.render_error_code);
			result.setMsg("请设置代理商价格!");
			return result;
		}
		
		if(plevel==3&&price!=null){
			organ.set(Organization.column_priceIds, price.getStr("ids"));
		}
		if(plevel==4&&StringUtils.isBlank(organ.getStr(Organization.column_priceIds))){
			String ppriceIds=Organization.dao.findById(organ.getStr(Organization.column_parentIds)).getStr(Organization.column_priceIds);
			if(StringUtils.isNotBlank(ppriceIds)){
				organ.set(Organization.column_priceIds ,ppriceIds);
			}
		}
		
		organ.set(Organization.column_addTime, new Date())
				.set(Organization.column_orderid, orderid)
				.set(Organization.column_bh, createBH(orderid, pBh, plevel))
				.set(Organization.column_level, plevel)
				.set(Organization.column_levelIds, OrganLevel.dao.getIdsByLevel(plevel));
				if( StringUtils.isNotBlank(organ.getStr(Organization.column_xzqh))){
					organ.set(Organization.column_xzqh, Code.cacheGet(organ.getStr(Organization.column_xzqh)).getStr(Code.column_code));
				}else{
					Organization parentOrgan2 = Organization.dao.findById(parentOrgan.getStr(Organization.column_parentIds));
					if(parentOrgan2!=null){
						if(parentOrgan2.getStr(Organization.column_name).equals("北京市")||parentOrgan2.getStr(Organization.column_name).equals("天津市")||parentOrgan2.getStr(Organization.column_name).equals("上海市")||parentOrgan2.getStr(Organization.column_name).equals("重庆市"))
						organ.set(Organization.column_xzqh,parentOrgan.getStr(Organization.column_xzqh));
					}
					
				}
				organ.save(organIds);
		
		//用户不为空可以设置部门等等--
		if (StringUtils.isNotBlank(username)) {
			User oldUser = User.cacheGetByUserName(user.getStr(User.column_username));
				if (null == oldUser) {
					// 初始化部门
					String deptIds = ToolRandoms.getUuid(true);
					new Department().set(Department.column_name, organ.get(Organization.column_name))
							.set(Department.column_level, 0).set(Department.column_orderid, 1)
							.set(Department.column_bh, "01").set(Department.column_organizationids, organIds)
							.save(deptIds);

					// 初始化岗位
					String stationIds = ToolRandoms.getUuid(true);
					new DeptStation().set(DeptStation.column_name, organ.get(Organization.column_name))
							.set(DeptStation.column_level, 0).set(DeptStation.column_orderid, 1)
							.set(DeptStation.column_departmentids, deptIds).set(DeptStation.column_organIds, organIds)
							.save(stationIds);

					// 初始化用户
					String userIds = ToolRandoms.getUuid(true);
					// 初始化用户
					user.set(User.column_departmentids, deptIds).set(User.column_stationids, stationIds).set(User.column_verificationCode, "01")
							.set(User.column_organizationids, organIds);
					// 密码加密
					byte[] salt = ToolPbkdf2.generateSalt();// 密码盐
					byte[] encryptedPassword = ToolPbkdf2.getEncryptedPassword("888888", salt);
					user.set(User.column_salt, Base64.encodeBase64String(salt));
					user.set(User.column_password, Base64.encodeBase64String(encryptedPassword));

//					// 初始化idea密钥
//					String secretKey = Base64.encodeBase64String(ToolIDEA.initKey());
//					user.set(User.column_secretkey, secretKey);

					// 保存用户
					user.set(User.column_status, "1");
					new UserService().save(userIds, user, "888888", null);
					//user.save(userIds);

					// 缓存
					User.cacheAdd(user.getPKValue());

					// 跟新代理人
					organ.set(Organization.column_agentIds, userIds).update();

					// 初始化用户岗位权限
					String levelIds = Db.findFirst("select ids from sys_organ_level where level = ?",
							organ.getInt(Organization.column_level)).getStr(OrganLevel.column_ids);
					List<Record> olrs = Db.find("select ids,rightIds from sys_organ_level_right where levelIds = ?",
							levelIds);
					if (olrs.size() > 0) {
						Iterator<Record> it = olrs.iterator();
						if (cancelNodes.size() > 0) {
							while (it.hasNext()) {
								Record r = it.next();
								for (ZtreeNode node : cancelNodes) {
									if (r.getStr("rightIds").equals(node.getId())) {
										it.remove();
									}
								}
							}
						}
						for (Record r : olrs) {
							String ids = ToolRandoms.getUuid(true);
							new DeptStationRight().set(DeptStationRight.column_ids, ids)
									.set(DeptStationRight.column_stationIds, stationIds)
									.set(DeptStationRight.column_rightIds, r.getStr("rightIds")).save(ids);
						}
					}

					// 添加岗位权限缓存
					DeptStationService.cacheAdd(stationIds);

				}else {
					result.setCode(ConstantRender.render_error_code);
					result.setMsg("该用户名已经被其他人占用，请修改后重试!");
					//throw new RuntimeException("用户名已存在!");
					return result;
					
				}
			
		} 
		}else{
			result.setCode(ConstantRender.render_error_code);
			result.setMsg("该店名已经被其他人占用，请修改后重试!");
			//throw new RuntimeException("机构已存在!");
			return result;
		}
		
		
		result.setCode(ConstantRender.render_success_code);
		return result;
	}
	
	/**
	 * 修改机构
	 * @param cancelNodes
	 * @param organ
	 * @param user
	 * @return
	 */
	@Before(Tx.class)
	public RenderBean upOrgan(List<ZtreeNode> changeNodes, Organization organ, User user) {
		RenderBean result = new RenderBean();
		
		if(null != organ.getPKValue()){
			//跟新机构信息
			if(StringUtils.isNotBlank(organ.getStr(Organization.column_xzqh))){
				organ.set(Organization.column_xzqh,Code.cacheGet(organ.getStr(Organization.column_xzqh)).getStr(Code.column_code)).update();
			}else{
				organ.update();
			}
			//organ.update();
			
			//跟新根部门信息
			Department dept = Department.dao.findFirst(getSqlMy(Department.sqlId_rootDeptByOrgan), organ.getPKValue());
			if(null != dept){
				dept.set(Department.column_name, organ.getStr(Organization.column_name)).update();
			}
			
			//跟新根岗位信息
			DeptStation station = DeptStation.dao.findFirst(getSqlMy(DeptStation.sqlId_rootStationByOrgan), organ.getPKValue());
			if(null != station){
				station.set(DeptStation.column_name, organ.getStr(Organization.column_name)).update();
			}
		
			if(null != user.getPKValue()){
				//跟新代理人信息
				user.update();
			}
		
			List<DeptStation> stations = DeptStation.dao.find(getSqlMy(DeptStation.sqlId_allStationByOrgan), organ.getPKValue());
			if(changeNodes.size() > 0){
				//跟新代理人权限
				for(ZtreeNode changeNode : changeNodes){
					//待删除节点
					if("false".equals(changeNode.getChecked())){
						delStationRight(stations, changeNode);
						
					}
					//全选状态
					if("true".equals(changeNode.getChecked()) && "false".equals(changeNode.getIsHalf())){
						addStationRight(station, changeNode, organ.getInt(Organization.column_level));
					}
					//半选状态
					if("true".equals(changeNode.getChecked()) && "true".equals(changeNode.getIsHalf())){
						if(null != station){
							DeptStationRight dsr = DeptStationRight.dao.findByIds(changeNode.getId(), station.getPKValue());
							if(null == dsr){
								new DeptStationRight().set(DeptStationRight.column_rightIds, changeNode.getId())
								   .set(DeptStationRight.column_stationIds, station.getPKValue()).save();
							}
						}
					}
				}
			}
		
			//跟新岗位缓存
			if(stations.size() > 0){
				for(DeptStation s : stations){
					DeptStationService.cacheAdd(s.getPKValue());
				}
			}
		}	
		result.setCode(ConstantRender.render_success_code);
		return result;
	}
	
	//添加根岗位权限
	public void addStationRight(DeptStation station, ZtreeNode addNode, int level){
		//添加自己
		if(null != station){
			DeptStationRight dsr = DeptStationRight.dao.findByIds(addNode.getId(), station.getPKValue());
			if(null == dsr){
				new DeptStationRight().set(DeptStationRight.column_rightIds, addNode.getId())
				   .set(DeptStationRight.column_stationIds, station.getPKValue()).save();
			}
		}
		
		//递归添加子节点
		if("true".equals(addNode.getIsParent())){
			addChildStationRight(addNode.getId(), station, level);
		}
		
	}
	
	//递归添加子节点
	public void addChildStationRight(String parentIds, DeptStation station, int level){
		String sql = getSqlMy(OrganLevelRight.sqlId_updateRightChildNode);
		List<Right> rights = Right.dao.find(sql, station.getPKValue(), level, parentIds);
		if (rights.size() > 0) {
			for (Right child : rights) {
				DeptStationRight dsr = DeptStationRight.dao.findByIds(child.getPKValue(), station.getPKValue());
				if (null == dsr) {
					new DeptStationRight().set(DeptStationRight.column_rightIds, child.getPKValue())
					   .set(DeptStationRight.column_stationIds, station.getPKValue()).save();
				}
				addChildStationRight(child.getPKValue(), station, level);
			}
		}
	}
	
	//删除所有岗位指定的权限
	public void delStationRight(List<DeptStation> stations, ZtreeNode delNode){
		//删除自己
		for(DeptStation station : stations){
			DeptStationRight dsr = DeptStationRight.dao.findByIds(delNode.getId(), station.getPKValue());
			if(null != dsr){
				dsr.delete();
			}
		}
		// 删除子节点
		if("true".equals(delNode.getIsParent())){
			delChildStationRight(delNode.getId(), stations);
		}
	}
	
	// 递归删除子节点
	public void delChildStationRight(String ids, List<DeptStation> stations) {
		Map<String, Object> queryParam = new HashMap<String, Object>();
		queryParam.put(Right.column_parentids, ids);
		List<Record> childs = find(Right.sqlId_childNode, queryParam);
		if (childs.size() > 0) {
			for (Record child : childs) {
				for(DeptStation station : stations){
					DeptStationRight dsr = DeptStationRight.dao.findByIds(child.getStr("ids"), station.getPKValue());
					if(null != dsr){
						dsr.delete();
					}
				}
				delChildStationRight(child.getStr("ids"), stations);
			}
		}
	}

	/**
	 * 机构tree节点数据
	 * 
	 * @param cxt
	 * @param parentIds
	 * @return
	 */
	public List<ZtreeNode> childNodeData(String cxt, String parentIds, String curOrganIds) {
		List<Organization> list = null;
		if (null != parentIds) {
			String sql = getSqlMy(Organization.sqlId_childNode);
			list = Organization.dao.find(sql, parentIds);

		} else {
			list = new ArrayList<>();
			list.add(Organization.dao.findById(curOrganIds));

		}

		List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
		ZtreeNode node = null;

		for (Organization organ : list) {
			node = new ZtreeNode();
			node.setId(organ.getPKValue());
			node.setName(organ.getStr(Organization.column_name));
			node.setBh(organ.getStr(Organization.column_bh));

			node.setIsParent(organ.getStr(Organization.column_isparent));
			node.setLevelNum(organ.getInt(Organization.column_level));
			node.setLevelIds(organ.getStr(Organization.column_levelIds));
			node.setIcon(cxt + ConstantRender.icon_path + organ.getStr(Organization.column_icon));
			nodeList.add(node);
		}

		return nodeList;
	}
	
	
	/**
	 * 机构tree节点数据
	 * 
	 * @param cxt
	 * @param parentIds
	 * @return
	 */
	public List<ZtreeNode> childNodeData2(String cxt, String parentIds) {
		List<Organization> list = null;
		String curOrganIds = "c9aebfe4912e4c07b4c7602b935154d6";
		if (null != parentIds) {
			String sql = getSqlMy(Organization.sqlId_childNode);
			list = Organization.dao.find(sql, parentIds);

		} else {
			list = new ArrayList<>();
			list.add(Organization.dao.findById(curOrganIds));

		}

		List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
		ZtreeNode node = null;

		for (Organization organ : list) {
			node = new ZtreeNode();
			node.setId(organ.getPKValue());
			node.setName(organ.getStr(Organization.column_name));
			node.setBh(organ.getStr(Organization.column_bh));

			node.setIsParent(organ.getStr(Organization.column_isparent));
			node.setLevelNum(organ.getInt(Organization.column_level));
			node.setLevelIds(organ.getStr(Organization.column_levelIds));
			node.setIcon(cxt + ConstantRender.icon_path + organ.getStr(Organization.column_icon));
			nodeList.add(node);
		}

		return nodeList;
	}
	

	/**
	 * 添加权限tree节点
	 * 
	 * @param cxt
	 * @param parentIds
	 * @param curLevelIds
	 * @return
	 */
	public List<ZtreeNode> rightChildNodeData(String cxt, String parentIds, int level) {
		List<Right> list = null;
		if (null != parentIds) {
			String sql = getSqlMy(OrganLevelRight.sqlId_selectRightChildNode);
			list = Right.dao.find(sql, level + 1, parentIds);
		} else {
			String sql = getSqlMy(OrganLevelRight.sqlId_selectRightRootNode);
			list = Right.dao.find(sql, level + 1);
		}
		List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
		ZtreeNode node = null;

		for (Right right : list) {
			node = new ZtreeNode();
			node.setId(right.getStr(Right.column_ids));
			node.setName(right.getStr(Right.column_name));
			node.setIsParent(right.getStr(Right.column_isparent));
			node.setChecked("true");
			node.setIcon(cxt + ConstantRender.icon_path + right.getStr(Right.column_icon));
			nodeList.add(node);
		}
		return nodeList;
	}
	
	/**
	 * 修改权限tree节点
	 * @param cxt
	 * @param parentIds
	 * @param level
	 * @return
	 */
	public List<ZtreeNode> upRightChildNodeData(String cxt, String parentIds, int level, String stationIds){
		List<Right> list = null;
		if (null != parentIds) {
			String sql = getSqlMy(OrganLevelRight.sqlId_updateRightChildNode);
			list = Right.dao.find(sql, stationIds, level, parentIds);
		} else {
			String sql = getSqlMy(OrganLevelRight.sqlId_updateRightRootNode);
			list = Right.dao.find(sql, stationIds, level);
		}
		List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
		ZtreeNode node = null;

		for (Right right : list) {
			node = new ZtreeNode();
			node.setId(right.getStr(Right.column_ids));
			node.setName(right.getStr(Right.column_name));
			node.setIsParent(right.getStr(Right.column_isparent));
			node.setChecked(right.getStr("checked"));
			node.setIcon(cxt + ConstantRender.icon_path + right.getStr(Right.column_icon));
			nodeList.add(node);
		}
		return nodeList;
		
	}

	/**
	 * 获取机构下用户节点
	 * 
	 * @param cxt
	 * @param ids
	 * @return
	 */
	public List<ZtreeNode> allOrganUserList(String cxt, String ids, String organIds) {
		List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
		ZtreeNode node = null;
		if (null == ids) {
			// 通过organIds查找部门根节点
			Organization organ = Organization.dao.findById(organIds);
			if (organ.getInt(Organization.column_level) == 2) {
				organIds = organ.getStr(Organization.column_parentIds);
			}
			String rootsql = getSqlMy(Department.sqlId_findRootByOrgan);
			Department rootDept = Department.dao.findFirst(rootsql, organIds);
			node = new ZtreeNode();
			node.setId(rootDept.getPKValue());
			node.setName(rootDept.getStr(Organization.column_name));
			node.setIsParent("true");
			node.setIcon(cxt + ConstantRender.icon_path + rootDept.getStr(Organization.column_icon));
			nodeList.add(node);
		} else {
			// 查找部门下所有用户
			String userSql = getSqlMy(User.sqlId_findUserByDept);
			List<User> userList = User.dao.find(userSql, ids);
			if (userList.size() > 0) {
				for (User user : userList) {
					node = new ZtreeNode();
					node.setId(user.getPKValue());
					node.setName(user.getStr(Organization.column_name));
					node.setIsParent("false");
					node.setIcon(cxt + ConstantRender.icon_path + user.getStr(Organization.column_icon));
					nodeList.add(node);
				}
			}
			// 通过ids查找指定部门下的子部门
			String childsql = getSqlMy(Department.sqlId_childNode);
			List<Department> deptList = Department.dao.find(childsql, ids);
			if (deptList.size() > 0) {
				for (Department dept : deptList) {
					node = new ZtreeNode();
					node.setId(dept.getPKValue());
					node.setName(dept.getStr(Organization.column_name));
					node.setIsParent("true");
					node.setIcon(cxt + ConstantRender.icon_path + dept.getStr(Organization.column_icon));
					nodeList.add(node);
				}
			}
		}
		return nodeList;
	}
	
	/**
	 * 获取机构price 节点tree
	 * @param cxt
	 * @param ids
	 * @param organIds
	 * @return
	 */
	public List<ZtreeNode> allOrganPricList(String cxt, String ids, String organIds){
		List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
		ZtreeNode node = null;
		if (null == ids) {
			// 通过organIds查找根节点
			Organization organ = Organization.dao.findById(organIds);
			//if (organ.getInt(Organization.column_level) == 2) {
				organIds = organ.getStr(Organization.column_parentIds);
				organ = Organization.dao.findById(organIds);
			//}
			node = new ZtreeNode();
			node.setId(organ.getPKValue());
			node.setName(organ.getStr(Organization.column_name));
			node.setIsParent("true");
			node.setIcon(cxt + ConstantRender.icon_path + organ.getStr(Organization.column_icon));
			nodeList.add(node);
		} else {
			// 查找机构下所有价格表
			List<Price> priceList = Price.dao.findByOrgan(ids);
			if (priceList.size() > 0) {
				for (Price price : priceList) {
					node = new ZtreeNode();
					node.setId(price.getPKValue());
					node.setName(price.getStr(Price.column_name));
					node.setIsParent("false");
//								node.setIcon(cxt + ConstantRender.icon_path + price.getStr(Price.column_icon));
					nodeList.add(node);
				}
			}
			// 通过ids查找指定机构下的子机构
//			String childsql = getSqlMy(Organization.sqlId_childNode);
//			List<Organization> organList = Organization.dao.find(childsql, ids);
//			if (organList.size() > 0) {
//				for (Organization organ : organList) {
//					node = new ZtreeNode();
//					node.setId(organ.getPKValue());
//					node.setName(organ.getStr(Organization.column_name));
//					node.setIsParent("true");
//					node.setIcon(cxt + ConstantRender.icon_path + organ.getStr(Organization.column_icon));
//					nodeList.add(node);
//				}
//			}
			
		}
		return nodeList;
	}
	
	/**
	 * 删除
	 * 
	 * @param ids
	 * @return
	 */
	public String delete(String ids) {
		Organization organ = Organization.dao.findById(ids);

		// 是否存在子节点
		if (organ.getStr(Organization.column_isparent).equals("true")) {
			return "存在子机构，不能直接删除"; // 存在子节点，不能直接删除
		}

		// 部门下是否存在人
		String countSql = getSqlMy(Organization.sqlId_userCount);
		long count = Db.use(ConstantInit.db_dataSource_main).queryNumber(countSql, ids).longValue();
		if (count != 0) {
			return "机构下下存在人员，不能删除"; // 部门下存在人，不能删除
		}

		// 修改上级节点的isparent
		Organization pOrgan = Organization.dao.findById(organ.getStr(Organization.column_parentIds));
		String sql = getSqlMy(Organization.sqlId_childCount);
		Record record = Db.use(ConstantInit.db_dataSource_main).findFirst(sql, pOrgan.getPKValue());
		Long counts = record.getNumber("counts").longValue();
		if (counts == 1) {
			pOrgan.set(Organization.column_isparent, "false");
			pOrgan.update();
		}

		// 删除
		Organization.dao.deleteById(ids);

		return ConstantRender.render_success;
	}

}
